package vipcard.meichehui.config;


import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import vipcard.meichehui.utill.R;
import vipcard.meichehui.utill.TheardCentx;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "html", urlPatterns = "/*")
@Slf4j
public class Feliter implements Filter {

    private static final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        log.info("拦截器开启");
        System.out.println("拦截开始");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        System.out.println(requestURI);
        String[] urls = new String[]{

                "/login",
                "/employee/logout",
                "/html/**",
                "/index.html/**",
                "/html/index.html",

                "/user/sendMsg",
                "/js/**",
                "/css/**",
                "/favicon.ico"

        };

        for (String url : urls) {

            if (matcher.match(url, requestURI)) {


                filterChain.doFilter(servletRequest, servletResponse);

                return;
            }


        }

        if (request.getSession().getAttribute("username") != null) {


            filterChain.doFilter(servletRequest, servletResponse);
            TheardCentx.setObjectThreadLocal((String) request.getSession().getAttribute("username"));
            return;

        }

        System.out.println(requestURI);

        System.out.println(request.getSession().getAttribute("username") + "2222222222222222222222");
        if (request.getSession().getAttribute("username") != null) {


            filterChain.doFilter(servletRequest, servletResponse);

            String user = (String) request.getSession().getAttribute("username");


            TheardCentx.setObjectThreadLocal(user);

            return;

        }


        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    @Override
    public void destroy() {

    }


}
